package com.hcinfos.gsoo.ui;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import com.alipay.android.app.sdk.AliPay;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.adapter.MyPayAdapter;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.GiftOrder;
import com.hcinfos.gsoo.enity.User;
import com.hcinfos.gsoo.interfaze.OrderCallback;
import com.hcinfos.gsoo.pay.Keys;
import com.hcinfos.gsoo.pay.Rsa;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.util.UtilHttp;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

/**
 * 我的积分兑换
 * 
 * @author john
 * 
 */
public class MyPayActivity extends Activity implements OnClickListener,
		OrderCallback {

	private ImageView back_iv;
	private ListView listView;
	private List<GiftOrder> list;
	private MyPayAdapter adapter;

	private SharePreferenceUtil util;

	private ObjectMapper mapper;
	private List<GiftOrder> giftList;

	private ProgressBar progress;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_pay);
		progress = (ProgressBar) findViewById(R.id.progress);
		list = new ArrayList<GiftOrder>();
		adapter = new MyPayAdapter(this, list);
		adapter.setCallback(this);
		back_iv = (ImageView) findViewById(R.id.back_iv);
		back_iv.setOnClickListener(this);
		util = new SharePreferenceUtil(this, "setting");

		listView = (ListView) findViewById(R.id.listView);
		listView.setAdapter(adapter);
		user = (User) util.loadObject("user");
		mapper = new ObjectMapper();
		obtainData();

	}

	private User user;
	public final int OBTAIN_SUCCESS = 0x2210;
	public final int OBTAIN_FAIL = OBTAIN_SUCCESS + 1;
	public final int RQF_PAY = OBTAIN_SUCCESS + 2;
	public final int OK_SUCCESS = OBTAIN_SUCCESS + 3;
	public final int OK_FAIL = OBTAIN_SUCCESS + 4;
	private int page = 1;
	private int rows = 50;

	private void obtainData() {

		if (user == null)
			return;
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		params.addBodyParameter("user.id", user.getId());
		params.addBodyParameter("page", page + "");
		params.addBodyParameter("rows", rows + "");

		http.send(HttpRequest.HttpMethod.POST, Urls.callnew_exchangeRecordList,
				params, new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {

						handler.sendEmptyMessage(OBTAIN_FAIL);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {

						try {

							String result = arg0.result;

							LogUtil.d("wxf", "result = " + result);

							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							if (state == 200) {
								String data = obj.getString("data");
								giftList = mapper.readValue(data,
										new TypeReference<List<GiftOrder>>() {
										});
								handler.sendEmptyMessage(OBTAIN_SUCCESS);
							} else {
								handler.sendEmptyMessage(OBTAIN_FAIL);
							}

						} catch (Exception e) {
							LogUtil.e("wxf", e.toString());
							handler.sendEmptyMessage(OBTAIN_FAIL);
						}
					}

				});
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			progress.setVisibility(View.GONE);
			switch (msg.what) {
			case OBTAIN_SUCCESS:
				if (giftList != null) {
					list.addAll(giftList);
				}
				adapter.setDataChange(list);
				break;
			case OBTAIN_FAIL:
				Toast.makeText(MyPayActivity.this, "获取失败!", 500).show();
				break;
			case RQF_PAY:
				list.clear();
				obtainData();
				break;
			case OK_SUCCESS:
				list.clear();
				obtainData();
				break;
			case OK_FAIL:
				list.clear();
				obtainData();
				Toast.makeText(MyPayActivity.this, "确认失败!", 500).show();
				break;
			}
		};
	};

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.back_iv:
			finish();
			break;
		}
	}

	/**
	 * 支付宝支付模块
	 */
	private void pay(String orderId, String giftName, String price) {
		String info = getOrderInfo(orderId, giftName, price);
		String sign = Rsa.sign(info, Keys.PRIVATE);
		sign = URLEncoder.encode(sign);
		info += "&sign=\"" + sign + "\"&" + getSignType();
		final String orderInfo = info;
		new Thread() {
			public void run() {
				AliPay alipay = new AliPay(MyPayActivity.this, handler);

				// 设置为沙箱模式，不设置默认为线上环境
				// alipay.setSandBox(true);
				String result = alipay.pay(orderInfo);
				Message msg = handler.obtainMessage();
				msg.what = RQF_PAY;
				msg.obj = result;
				handler.sendMessage(msg);
			}
		}.start();
	}

	private String getOrderInfo(String orderId, String giftName, String price) {
		StringBuilder sb = new StringBuilder();
		sb.append("partner=\"");
		sb.append(Keys.DEFAULT_PARTNER);
		sb.append("\"&out_trade_no=\"");
		sb.append(orderId);
		sb.append("\"&subject=\"");
		sb.append("礼品兑换订单");
		sb.append("\"&body=\"");
		sb.append(giftName);
		sb.append("\"&total_fee=\"");
		sb.append(price + "");
		sb.append("\"&notify_url=\"");

		// 网址需要做URL编码
		sb.append(URLEncoder
				.encode("http://www.gsoo.com/alipaySupport_busi_gift_pay_call_back.action"));
		sb.append("\"&service=\"mobile.securitypay.pay");
		sb.append("\"&_input_charset=\"UTF-8");
		sb.append("\"&return_url=\"");
		sb.append(URLEncoder.encode("http://m.alipay.com"));
		sb.append("\"&payment_type=\"1");
		sb.append("\"&seller_id=\"");
		sb.append(Keys.DEFAULT_SELLER);

		// 如果show_url值为空，可不传
		// sb.append("\"&show_url=\"");
		sb.append("\"&it_b_pay=\"1m");
		sb.append("\"");

		return new String(sb);
	}

	private String getSignType() {
		return "sign_type=\"RSA\"";
	}

	@Override
	public void callback(int command, String orderId) {

		switch (command) {
		case 0:
			String id = orderId.split(",")[0];
			String giftName = orderId.split(",")[1];
			String price = orderId.split(",")[2];
			pay(id, giftName, price);
			break;
		case 1:
			ok(orderId);
			break;
		}
	}

	private void ok(String id) {

		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		params.addBodyParameter("giftRecord.id", id);
		http.send(HttpRequest.HttpMethod.POST, Urls.callnew_confirmGetGift,
				params, new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						handler.sendEmptyMessage(OK_FAIL);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {

						String result = arg0.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							if (state == 200) {
								handler.sendEmptyMessage(OK_SUCCESS);
							} else {
								handler.sendEmptyMessage(OK_FAIL);
							}
						} catch (Exception e) {
							handler.sendEmptyMessage(OK_FAIL);

						}
					}

				});
	}
}
